#!/usr/bin/env bash

mkdir -f /tmp
PS1='$(echo -en "\033[34m")'
PS1+='$(date +%s)'
PS1+=' $( [ $? = 0 ] && echo -en "\033[32m" || echo -en "\033[31m" )$?'
PS1+=' $(echo -en "\033[33m")$(pwd)'
PS1+=' # $(echo -en "\033[0m")'

crash=/data/log/faultlog/temp/

function async_listen_crash() {
    local last=$(ls $crash | wc -l)
    while true; do
        sleep 1
        local now=$(ls $crash | wc -l)
        if [ "$last" != "$now" ]; then
            echo -e "\033[31mcrash! "$(ls -rt $crash | tail -$((now - last)))"\033[0m"
        fi
        last=$now
    done
}
async_listen_crash &

function ehelp() {
cat << EOF
    mleak: 用于查看泄漏的内存状态
    rtest: 运行测试
    acrash \$name: 解析crash
    acrash_map \$name: 解析crash的maps
EOF
}

function ll() {
    /system/bin/ls -l --color $*
}

function la() {
    /system/bin/ls -la --color $*
}

function mleak() {
    cat /proc/meminfo | tail -1
    for id in $(ls /proc/); do
        if [ -d /proc/$id/fd ]; then
            ls -l /proc/$id/fd | grep "dmabuf" 1>/dev/null 2>/dev/null
            if [ "$?" = "0" ]; then
                echo -en " fd: $(ls -l /proc/$id/fd | grep "dmabuf" | wc -l 2>/dev/null)"
                echo -en " pid: $id"
                echo -en " name: "$(cat /proc/$id/status | head -1 | cut -d: -f2-)
                echo -e ""
            fi
        fi
    done
}

function acrash() {
    local name=$1
    if [ "$name" = "" ]; then
        echo "需要一个参数"
    fi
    linenumber=$(grep -n "^Maps:" $crash/$name | cut -d: -f1)
    ((linenumber -= 2))
    sed -n "1,${linenumber}p" $crash/$name
}

function acrash_map() {
    local name=$1
    if [ "$name" = "" ]; then
        echo "需要一个参数"
    fi
    linenumber=$(grep -n "^Maps:" $crash/$name | cut -d: -f1)
    sed -n "$linenumber,\$p" $crash/$name
}

function rtest() {
    mount -o remount,rw /
    mkdir -p /tmp
    cd /data/test || return
    rm -f *.xml
    chmod u+x *
    ls | grep _test > ../tests
    sed -i 's/^/.\//g' ../tests
    sed -i 's/$/ --gtest_color=yes/g' ../tests
    sed -i 's/$/ || echo -en "\\n\\n\\n\\n\\n! $!\\n\\n\\n\\n\\n"/g' ../tests
    sed -i 's/$/ && exit 1/g' ../tests
    source ../tests
}
